﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _06.MultiValueDictionary
{
    class MultiValueDictionary<K, V> : IEnumerable<KeyValuePair<K, List<V>>>
    {
        Dictionary<K, List<V>> table;
        int count;

        public MultiValueDictionary()
        {
            this.table = new Dictionary<K, List<V>>();
            count = 0;
        }

        #region Properties

        public int Count
        {
            get
            {
                return count;
            }
        }

        public List<V> this[K key]
        {
            get
            {
                return table[key];
            }
            set
            {
                table[key] = value;
            }
        }

        public ICollection<V> Values
        {
            get
            {
                List<V> values = new List<V>();
                foreach (KeyValuePair<K, List<V>> item in table)
                {
                    values.AddRange(item.Value);
                }
                return values;
            }
        }

        public ICollection<K> Keys
        {
            get
            {
                List<K> keys = new List<K>();
                foreach (KeyValuePair<K, List<V>> item in table)
                {
                    keys.Add(item.Key);
                }
                return keys;
            }
        }

        #endregion

        #region Methods

        public void Add(K key, V value)
        {
            if (table.ContainsKey(key))
            {
                table[key].Add(value);
            }
            else
            {
                table.Add(key, new List<V>() { value });
            }
            count++;
        }

        public void Remove(K key)
        {
            count -= table[key].Count;
            table.Remove(key);
        }

        public void Clear()
        {
            table = new Dictionary<K, List<V>>();
            count = 0;
        }

        public bool ContainsKey(K key)
        {
            return table.ContainsKey(key);
        }

        #endregion

        #region IEnumerable

        public IEnumerator<KeyValuePair<K, List<V>>> GetEnumerator()
        {
            foreach (KeyValuePair<K, List<V>> pair in this.table)
            {
                yield return pair;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return ((IEnumerable<KeyValuePair<K, List<V>>>)this).GetEnumerator();
        }

        #endregion
    }
}
